import pytest
from common.request_util import send
import jmespath
from loguru import logger
from common import log_util
from config.project_baseinfo import *
from common.file_util import write_extract_variable, clear_extract_variable, clear_buy_system_shopping_variable
from common.db_util import *
@pytest.fixture(scope='session', autouse=True)
def get_client_token():
    '''
    获取token
    :return:
    '''
    try:
        data = {
            'path':'/api/login',
            'method':'post',
            'json':{"account":client['username'],"password":client['password']}
        }
        req = send('获取token',**data)
        token = req.json()['data']['token']
        write_extract_variable('token',token)
        # token1 = jmespath.search('data.token',req.json())
    except Exception as e:
        logger.error(f'获取token失败：{e}')


@pytest.fixture(scope='session', autouse=True)
def get_manage_token():
    '''
    获取管理端token
    :return:
    '''
    try:
        data = {
            'path':'/adminapi/login',
            'method':'post',
            'json':{"account":manage['use'],"pwd":manage['pwd'],"imgcode":"1"}
        }
        req = send('获取管理端token',**data)
        manage_token = req.json()['data']['token']
        write_extract_variable('manage_token',manage_token)
        # token1 = jmespath.search('data.token',req.json())
    except Exception as e:
        logger.error(f'获取token失败：{e}')

@pytest.fixture(scope='session', autouse=True)
def clear_all():
    '''
    清除上次测试变量
    :return:
    '''
    clear_extract_variable()
    clear_buy_system_shopping_variable()

@pytest.fixture(scope='function', autouse=True)
def db():
    '''
    开始的时候连接数据库，结束的时候关闭数据库
    :return:
    '''
    DBUtil()
    yield
    DBUtil().close_db()


